package com.zspringboot.demo.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zspringboot.demo.common.Result;
import com.zspringboot.demo.controller.dto.TitleOptions;
import com.zspringboot.demo.entity.TargetTitle;
import com.zspringboot.demo.service.ISpecificContentService;
import com.zspringboot.demo.service.ITargetTitleService;
import io.swagger.models.auth.In;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 项目标题 前端控制器
 * </p>
 *
 * @author laolang
 * @since 2024-03-12
 */
@RestController
@RequestMapping("/target-title")
public class TargetTitleController {


    @Resource
    private ITargetTitleService targetTitleService;

    @Resource
    private ISpecificContentService iSpecificContentService;
    @PostMapping("/a")
    public Result save(@RequestBody Map<String,Object> map){
        System.out.println("----------------------------------------");
        System.out.println(map.keySet());
        System.out.println(map.get("targetTitle"));
        System.out.println(map.get("targetTitle"));
        Map<String,Object> obj1 = (Map<String, Object>) map.get("targetTitle");
        Map<String,Object> obj2 = (Map<String, Object>) map.get("value1");
        System.out.println(obj1.keySet());
        System.out.println(obj1);
        System.out.println(obj1.get("id"));
        System.out.println(obj1.get("title"));
        System.out.println(obj1.get("contents"));
        System.out.println(obj1.get("userId"));
        System.out.println(obj1.get("remarks"));

        return null;

    }
    // 新增/修改
    @PostMapping()
    public Result save(
    @RequestBody Map map,@RequestBody String a
//            @RequestParam TargetTitle targetTitle,
//            @RequestParam List<Integer> value1
        ) throws JsonProcessingException {
//        System.out.println(value1 +"----------------------------");
//        System.out.println(targetTitle.toString());
//            value1.forEach(System.out::println);
        System.out.println(map.get("value1"));
//        System.out.println(map.get("targetTitle")); // 字符集  {id=1, title=互啄, contents=1, userId=1, remarks=菜鸡互啄}
//        String jsonInput = (map.get("targetTitle").toString())
//                .replaceAll("=", ":")
//                .replaceAll(", ", ", \"")
//                .replaceAll("\\{", "{\"")
//                .replaceAll("}", "\"}");

        // 去除大括号和空格
        String input = map.get("targetTitle").toString().replaceAll("[{}]", "");

        // 分割键值对并添加双引号
        String[] pairs = input.split(", ");
        StringBuilder jsonBuilder = new StringBuilder("{");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=");
            jsonBuilder.append("\"").append(keyValue[0]).append("\":");
            // 如果值是数字，则直接拼接，否则加双引号
            if (keyValue[1].matches("-?\\d+(\\.\\d+)?")) {
                jsonBuilder.append(keyValue[1]);
            } else {
                jsonBuilder.append("\"").append(keyValue[1]).append("\"");
            }
            jsonBuilder.append(",");
        }
        // 删除最后一个逗号
        jsonBuilder.deleteCharAt(jsonBuilder.length() - 1);
        jsonBuilder.append("}");


        ObjectMapper objectMapper = new ObjectMapper();
        TargetTitle  objT = objectMapper.readValue(jsonBuilder.toString(),TargetTitle.class);
        List<Integer> value11 = (List<Integer>) map.get("value1");
        AtomicReference<String> counts = iSpecificContentService.getSpecific(objT.getId(),value11);
        objT.setContents(counts+"");
        return Result.success(targetTitleService.saveOrUpdate(objT));
    }
//    @PostMapping
//    public Result save(
//            @RequestBody TargetTitle targetTitle,
//            @RequestBody Object value1) {
////            value1.forEach(System.out::println);
//            return Result.success(targetTitleService.saveOrUpdate(targetTitle));
//    }

    // 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
            return Result.success(targetTitleService.removeById(id));
            }
    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBacth(@RequestBody List<Integer> ids){
        return Result.success(targetTitleService.removeByIds(ids));
        }
    // 查询所有数据
    @GetMapping
    public Result findAll() {
            return Result.success(targetTitleService.list());
            }

    // 根据id 查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
            return Result.success(targetTitleService.getById(id));
            }

    // 分页
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam(defaultValue = "") String userId) {
            QueryWrapper<TargetTitle> queryWrapper = new QueryWrapper<>();
        if (!"".equals(userId))
            queryWrapper.eq("user_id",userId).or();
            queryWrapper.eq("user_id",0);
            return Result.success(targetTitleService.page(new Page<>(pageNum, pageSize),queryWrapper));
            }

    // 返回前端项目下数据选项是，填充多选框
    @GetMapping("/controllerId/{id}")
    public Result controllerId(@PathVariable Integer id){
        List<TitleOptions> list = targetTitleService.getContentS(id);
        Object json = JSONArray.toJSON(list);
        return Result.success(json);
    }
}

